using System.Collections;
using Castle.DynamicProxy;

namespace NUtil.beans {
    internal class ProxyGeneratorFacade {
        public static T CreateProxy<T>() {
            ProxyGenerator proxyGenerator = new ProxyGenerator();
            return (T) proxyGenerator.CreateProxy(typeof (T), new Interceptor(), new object());
        }

        public class Interceptor : IInterceptor {
            private Hashtable propHash = new Hashtable();

            public object Intercept(IInvocation invocation, params object[] args) {
                if (isSetter(invocation)) {
                    propHash.Add(propertyName(invocation), args[0]);
                }
                else {
                    return propHash[propertyName(invocation)];
                }
                return null;
            }

            private static bool isSetter(IInvocation invocation) {
                return invocation.Method.Name.StartsWith("set");
            }

            private static string propertyName(IInvocation invocation) {
                return invocation.Method.Name.Remove(0, 3);
            }
        }
    }
}